#!/bin/bash

# 英语词汇量估算系统备份脚本
# 作者: 系统管理员
# 日期: $(date +%Y-%m-%d)

# 配置变量
BACKUP_DIR="/var/backups/englishvet"
LOG_DIR="/var/log/englishvet"
PROJECT_DIR="/var/www/englishvet"
RETENTION_DAYS=30

# 创建备份目录
mkdir -p $BACKUP_DIR
mkdir -p $LOG_DIR

# 获取当前时间戳
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME="englishvet_backup_$TIMESTAMP"

# 日志文件
LOG_FILE="$LOG_DIR/backup_$TIMESTAMP.log"

# 开始备份
echo "开始备份 - $(date)" | tee -a $LOG_FILE

# 1. 备份数据库
echo "备份数据库..." | tee -a $LOG_FILE
if [ -f "$PROJECT_DIR/vocabulary.db" ]; then
    cp "$PROJECT_DIR/vocabulary.db" "$BACKUP_DIR/${BACKUP_NAME}_database.db"
    echo "数据库备份完成: ${BACKUP_NAME}_database.db" | tee -a $LOG_FILE
else
    echo "警告: 数据库文件不存在" | tee -a $LOG_FILE
fi

# 2. 备份配置文件
echo "备份配置文件..." | tee -a $LOG_FILE
mkdir -p "$BACKUP_DIR/${BACKUP_NAME}_config"
cp -r "$PROJECT_DIR"/*.py "$BACKUP_DIR/${BACKUP_NAME}_config/" 2>/dev/null
cp -r "$PROJECT_DIR"/*.txt "$BACKUP_DIR/${BACKUP_NAME}_config/" 2>/dev/null
cp -r "$PROJECT_DIR"/*.md "$BACKUP_DIR/${BACKUP_NAME}_config/" 2>/dev/null
echo "配置文件备份完成" | tee -a $LOG_FILE

# 3. 备份数据文件
echo "备份数据文件..." | tee -a $LOG_FILE
if [ -d "$PROJECT_DIR/data" ]; then
    cp -r "$PROJECT_DIR/data" "$BACKUP_DIR/${BACKUP_NAME}_data"
    echo "数据文件备份完成" | tee -a $LOG_FILE
fi

if [ -d "$PROJECT_DIR/english-wordlists" ]; then
    cp -r "$PROJECT_DIR/english-wordlists" "$BACKUP_DIR/${BACKUP_NAME}_wordlists"
    echo "词汇库备份完成" | tee -a $LOG_FILE
fi

# 4. 创建压缩包
echo "创建压缩包..." | tee -a $LOG_FILE
cd $BACKUP_DIR
tar -czf "${BACKUP_NAME}.tar.gz" "${BACKUP_NAME}_database.db" "${BACKUP_NAME}_config" "${BACKUP_NAME}_data" "${BACKUP_NAME}_wordlists" 2>/dev/null

# 清理临时文件
rm -rf "${BACKUP_NAME}_config" "${BACKUP_NAME}_data" "${BACKUP_NAME}_wordlists"

# 5. 删除旧备份
echo "清理旧备份..." | tee -a $LOG_FILE
find $BACKUP_DIR -name "englishvet_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete
find $BACKUP_DIR -name "englishvet_backup_*.db" -mtime +$RETENTION_DAYS -delete

# 6. 检查备份大小
BACKUP_SIZE=$(du -h "${BACKUP_NAME}.tar.gz" | cut -f1)
echo "备份文件大小: $BACKUP_SIZE" | tee -a $LOG_FILE

# 7. 验证备份
echo "验证备份..." | tee -a $LOG_FILE
if [ -f "${BACKUP_NAME}.tar.gz" ]; then
    tar -tzf "${BACKUP_NAME}.tar.gz" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "备份验证成功" | tee -a $LOG_FILE
    else
        echo "错误: 备份验证失败" | tee -a $LOG_FILE
        exit 1
    fi
else
    echo "错误: 备份文件未创建" | tee -a $LOG_FILE
    exit 1
fi

# 8. 记录备份信息
echo "备份完成 - $(date)" | tee -a $LOG_FILE
echo "备份文件: ${BACKUP_NAME}.tar.gz" | tee -a $LOG_FILE
echo "备份大小: $BACKUP_SIZE" | tee -a $LOG_FILE
echo "保留天数: $RETENTION_DAYS" | tee -a $LOG_FILE

# 9. 发送通知（可选）
# 如果有邮件配置，可以在这里添加邮件通知代码

echo "备份脚本执行完成" | tee -a $LOG_FILE 